<?php
namespace app\common\model;

use think\facade\Db;
use think\facade\Cache;
use hema\wechat\Driver;
use hema\wechat\Map;

/**
 * 用户认证申请模型
 */
class Apply extends BaseModel
{
    // 定义表名
    protected $name = 'apply';

    // 定义主键
    protected $pk = 'apply_id';

    // 追加字段
    protected $append = [
        'details'
    ];

    /**
     * 用户详情表
     */
    public function getDetailsAttr($value,$data)
    {
        return UserDetail::getDetail(['user_id' => $data['user_id']]);
    }

    /**
     * 关联用户表
     */
    public function user()
    {
        return $this->belongsTo('app\\common\\model\\User');
    }

    /**
     * 认证类型
     */
    public function getApplyModeAttr($value)
    {
        $status = [10 => '小程序申请', 20 => '商户入驻', 30 => '支付认证', 40 => '代理认证', 50 => '实名认证'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 认证类型
     */
    public function getAuthModeAttr($value)
    {
        $status = [10 => '工商', 20 => '个人'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 代理级别
     */
    public function getAgentModeAttr($value)
    {
        $status = [10 => '区县', 20 => '市级', 30 => '省级'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 付款状态
     */
    public function getPayStatusAttr($value)
    {
        $status = [10 => '待付款', 20 => '已付款', 30 => '免费认证'];
        return ['text' => $status[$value], 'value' => $value];
    }

   /**
     * 当前类型
     */
    public function getApplyStatusAttr($value)
    {
        $status = [10 => '待审核', 20 => '验证中', 30 => '认证成功', 40 => '被驳回'];
        return ['text' => $status[$value], 'value' => $value];
    }
    /**
     * 获取认证申请列表
     */
    public function getList($apply_mode = 0, $user_id = 0, $agent_id = 0)
    {
        $filter = [];
        $apply_mode > 0 && $filter['apply_mode'] = $apply_mode;
        $user_id > 0 && $filter['user_id'] = $user_id;
        $agent_id > 0 && $filter['agent_id'] = $agent_id;
        // 执行查询
        return $this->with(['user'])
            ->where($filter)
            ->order('apply_id','desc')
            ->paginate(['list_rows'=>15,'query' => request()->param()]);
    }

    /**
     * 详情
     */
    public static function detail($id)
    {
        return self::with(['user'])->find($id);
    }

    /**
     * 详情
     */
    public static function getApply(array $filter)
    {
        return self::with(['user'])->where($filter)->order('apply_id','desc')->find();
    }

    /**
     * 数据操作
     */
    public function action($data)
    {
        //判断是否为修改操作
        if($this->apply_id){
            //如果是小程序提交审核
            if($data['apply_status'] == 20){
                $wx = new Driver;
                $result = $wx->fastRegisterWeApp($data['details']);
                if($result['errcode'] != 0){
                    $this->error = 'Code：'.$result['errcode'].'，Msg：'.$result['errmsg'];
                    return false;
                }
            }
            //支付审核通过
            if($data['apply_status'] == 30 AND $this->apply_mode['value'] == 30){
                $setting = new Setting;
                if(!$setting->edit('payment',[
                    'wx' => [
                        'app_id' => $data['app_id'], //微信应用
                        'is_sub' => 1, //是否为特约商户
                        'mch_id' => $data['details']['mch_id'],//商户号
                        'api_key' => '',//密钥
                        'cert_pem' => '', //apiclient_cert.pem 证书
                        'key_pem' => '' //apiclient_key.pem 密钥
                    ],
                    'postpaid' => [0,0,0]
                ],$this->applet_id)){
                    $this->error = '支付设置失败';
                    return false;
                }
            }
            if($this->apply_mode['value'] == 40 AND $data['apply_status'] == 30){
                User::where('user_id',$this->user_id)->update(['status' => 30]);
            }
        }else{
            //添加操作
            //如果是代理申请
            if($data['apply_mode'] == 40){
                $map = new Map;
                if(!$location = $map->getLocation($data['location'])){
                    $this->error = $map->getError();
                    return false;
                }
                $data['province'] = $location['province'];
                $data['city'] = $location['city'];
                $data['district'] = $location['district'];
                $data['pay_status'] = 30;//免费认证
            }
            //如果是申请小程序
            if($data['apply_mode'] == 10){
                $webpay = Setting::getItem('webpay',0);//获取站点支付配置
                //判断是否收费
                if($webpay['cost']['applet_fee'] > 0){
                    $user = User::withoutGlobalScope()->where('user_id',$data['user_id'])->find();
                    if($user['money'] < $webpay['cost']['applet_fee']){
                        $this->error = '账户余额不足￥' . $webpay['cost']['applet_fee'] . '元，请先充值';
                        return false;
                    }
    				//用户扣费
    				$money = $user['money'] - $webpay['cost']['applet_fee'];//计算扣除后的余额
    				$user->money = ['dec',$webpay['cost']['applet_fee']];
    				$user->score = ['inc',$webpay['cost']['applet_fee']]; //增加积分
    				$user->pay = ['inc',$webpay['cost']['applet_fee']]; //增加消费金额
    				$user->save();
    				//生成交易记录
                    $order_list = [];
                    $order_no = order_no();
    				array_push($order_list,[
    					'user_type' => 20,
    					'action' => 40,//扣减
    					'order_no' => $order_no,
    					'money' => $webpay['cost']['applet_fee'],
    					'remark' => '小程序审核费',
    					'user_id' => $data['user_id']
    				]);
    				array_push($order_list,[
    					'user_type' => 40, //平台
    					'action' => 50,//分红
    					'order_no' => $order_no,
    					'money' => $webpay['cost']['applet_fee'],
    					'remark' => '小程序审核费'
    				]);
    				//添加流水记录
    				$model = new Record;
    				$model->saveAll($order_list);
                    //账户资金变动提醒
                    sand_account_change_msg('小程序审核费',$webpay['cost']['applet_fee'],$money,$data['user_id']);
                    $data['pay_status'] = 20;//认证费已支付
                }else{
                    $data['pay_status'] = 30;//免费认证
                }
            }
            $data['pay_time'] = time();//付款时间 
        }
        if(isset($data['user_id'])){
            $user_id = $data['user_id'];
        }else{
           $user_id = $this->user_id; 
        }
        // 开启事务
        Db::startTrans();
        try {

            $this->save($data);
            $model = new UserDetail;
            $model->action($data['details'],$user_id);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
    
    /**
     * 删除
     */
    public function remove()
    {
        return $this->delete();
    }






















    /**
     * 详情
     */
    public static function getDetail($where = [])
    {
        return self::withoutGlobalScope()->where($where)->find();
    }

    /**
     * 特约商户进件
     */
    public function applyment($data)
    {
        $account_name = $data['subject_type'] == 'SUBJECT_TYPE_INDIVIDUAL' ? $data['id_card_name'] : $data['merchant_name'];//开户名称
        return [
            'business_code' => $this['business_code'],          //业务申请编号
            'contact_info' => [             //超级管理员信息（全部加密）
                'contact_name' => $this->getEncrypt($data['id_card_name']),//姓名
                'contact_id_number' => $this->getEncrypt($data['id_card_number']),//身份证号
                //'openid' => '',   //微信号
                'mobile_phone' => $this->getEncrypt($data['mobile_phone']),     //手机号
                'contact_email' => $this->getEncrypt($data['contact_email'])        //邮箱
            ],
            'subject_info' => [         //主体资料
                'subject_type' => $data['subject_type'],        //主体类型
                'business_license_info' => [    //营业执照
                    'license_copy' => 'MediaID',        //营业执照照片
                    'license_number' => $data['license_number'],    //统一社会信用代码
                    'merchant_name' => $data['merchant_name'],      //营业执照名称
                    'legal_person' => $data['id_card_name']     //法人姓名
                ],  
                'identity_info' => [    //法人身份证件
                    'id_doc_type' => 'IDENTIFICATION_TYPE_IDCARD',
                    'id_card_info' => [ //身份证信息
                        'id_card_copy' => 'MediaID',    //正面图
                        'id_card_national' => 'MediaID',    //反面图
                        'id_card_name' => $this->getEncrypt($data['id_card_name']), //姓名（加密）
                        'id_card_number' => $this->getEncrypt($data['id_card_number']), //号码（加密）
                        'card_period_begin' => $data['card_period_begin'],  //有效期开始时间
                        'card_period_end' => $data['card_period_end']   //结束时间
                    ],
                    'owner' => true,        //法人是否为受益人
                ]
            ],
            'business_info' => [        //经营资料
                'merchant_shortname' => $data['merchant_shortname'],        //商户简称
                'service_phone' => $data['mobile_phone'],   //客服电话如：051699999999
                'sales_info' => [       //经营场景
                    'sales_scenes_type' => [
                        'SALES_SCENES_MINI_PROGRAM' //小程序
                    ],
                    'mini_program_info' => [//小程序场景
                        'mini_program_sub_appid' => ''  //商家小程序APPID
                    ]
                ]
            ],
            'settlement_info' => [      //结算规格
                'settlement_id' => $data['subject_type'] == 'SUBJECT_TYPE_INDIVIDUAL' ? '719' : '716',      //入驻结算规则ID,个体户=719 企业=716
                'qualification_type' => $data['qualification_type'],    //所属行业
                'qualifications' => [   //特殊行业资质图片 如食品经营许可证
                    'MediaID'
                ]
            ],
            'bank_account_info' => [    //结算银行账户
                'bank_account_type' => $data['subject_type'] == 'SUBJECT_TYPE_INDIVIDUAL' ? 'BANK_ACCOUNT_TYPE_PERSONAL' : 'BANK_ACCOUNT_TYPE_CORPORATE',       //账户类型 BANK_ACCOUNT_TYPE_CORPORATE：对公银行账户 BANK_ACCOUNT_TYPE_PERSONAL：经营者个人银行卡
                'account_name' => $this->getEncrypt($account_name), //开户名称(加密) 个体法人名称/公司全称
                'account_bank' => $data['account_bank'],        //开户银行 如工商银行
                'bank_address_code' => $data['bank_address_code'],      //开户银行省市编码
                'bank_name' => $data['bank_name'],  //开户银行全称
                'account_number' => $this->getEncrypt($data['account_number'])  //银行账号(加密)
            ]
        ];
    }
}
